package com.example.myapplication1.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

public class PreferenceManager {
    private static final String TAG = "PreferenceManager";
    private static final String PREF_NAME = "UserPrefs";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_PHONE = "phone";
    private static final String KEY_BALANCE = "balance";
    private static final float INITIAL_BALANCE = 20.0f;

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

    public PreferenceManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public void setLoggedIn(boolean isLoggedIn) {
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
        editor.apply();
        Log.d(TAG, "Login status set to: " + isLoggedIn);
    }

    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public void setUserId(long userId) {
        editor.putLong(KEY_USER_ID, userId);
        editor.apply();
        Log.d(TAG, "User ID set to: " + userId);
    }

    public long getUserId() {
        return sharedPreferences.getLong(KEY_USER_ID, -1);
    }

    public void setUsername(String username) {
        editor.putString(KEY_USERNAME, username);
        editor.apply();
        Log.d(TAG, "Username set to: " + username);
    }

    public String getUsername() {
        return sharedPreferences.getString(KEY_USERNAME, "");
    }

    public void setPhone(String phone) {
        editor.putString(KEY_PHONE, phone);
        editor.apply();
    }

    public String getPhone() {
        return sharedPreferences.getString(KEY_PHONE, "未设置");
    }

    public void setBalance(double balance) {
        editor.putFloat(KEY_BALANCE, (float) balance);
        editor.apply();
        Log.d(TAG, "Balance set to: " + balance);
    }

    public double getBalance() {
        return sharedPreferences.getFloat(KEY_BALANCE, INITIAL_BALANCE);
    }

    public void clearSession() {
        editor.clear();
        editor.apply();
        Log.d(TAG, "Session cleared");
    }

    public void initializeNewUser(String username, String phone, long userId) {
        setUsername(username);
        setPhone(phone);
        setUserId(userId);
        setBalance(INITIAL_BALANCE);
        setLoggedIn(true);
        Log.d(TAG, "New user initialized with balance: " + INITIAL_BALANCE);
    }
} 